/**
 *
 * @author Roninwz
 * @date 2019/1/3 14:20
 * @since 1.0.0
 */

const myUtil = {};

/**
 * 获取客户端ip
 * @param req  请求
 * @returns {string}
 */
myUtil.getClientIp = function (req) {
  return req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
};

/**
 * 生成随机 字符串数
 * @param length
 * @returns {string}
 */
myUtil.randomLength = function (length) {
  let _Length = length || 6;
  let randomNumber = Math.round(Math.random() * Math.pow(10, _Length));
  let randomStr = randomNumber + "";
  if (randomStr.length < _Length) {
    for (let i = 0; i < _Length - randomStr.length;) {
      randomStr = "0" + randomStr;
    }
  }
  return randomStr;
};

/**
 * 生成指定范围内的随机数  可以等于最大或最小数
 * @param max  最大
 * @param min  最小
 * @returns {*}
 */
myUtil.randomRangeInt = function (max, min) {
  min = min || 0;
  // Math.floor  向下取整
  let result = min + Math.floor(Math.random() * (max + 1 - min));
  if (result > max) {
    result = max;
  }
  return result;
};

/**
 * 判断一个字符串是否包含另一个字符串
 * @param conStr  长字符串
 * @param conStrEd  短字符串  被包含
 * @returns {boolean}
 */
myUtil.isContainStr = function (conStr, conStrEd) {
  if (conStr.indexOf(conStrEd) !== -1) {
    return true
  } else {
    return false;
  }
};

/**
 *  判断字符串是否为空或者空串
 * @param str
 * @returns {boolean}
 */
myUtil.isEmptyStr = function (str) {

  return str === null || str === '';
};

/**
 *  字符串反转
 * @param str
 * @returns {*}
 */
myUtil.reverseStr = function (str) {
  if (str === null || str === '') {
    return str;
  }
  return str.split("").reverse().join("");
};

/**
 *  判断两个对象是否相等
 * @param obj1
 * @param obj2
 * @returns {boolean}
 */
myUtil.diffObj = function (obj1, obj2) {
  // var a = {name: {sex: 'man'}};
  // var b = {name: {sex: 'man'}};  a b true
  // var c = ['a', 'b'];
  // var d = ['a', 'b'];  c d true
  // var e = [{name: 'wz'}, {password: '123'}];
  // var f = [{name: 'wz'}, {password: '123'}];  e f true

  let o1 = obj1 instanceof Object;
  let o2 = obj2 instanceof Object;
  if (!o1 || !o2) {/*  判断不是对象  */
    return obj1 === obj2;
  }

  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }

  for (let attr in obj1) {
    let t1 = obj1[attr] instanceof Object;
    let t2 = obj2[attr] instanceof Object;
    if (t1 && t2) {
      return myUtil.diffObj(obj1[attr], obj2[attr]);
    } else if (obj1[attr] !== obj2[attr]) {
      return false;
    }
  }
  return true;
};


module.exports = myUtil;
